<template>
  <view class="container">
    <!-- 地址列表 -->
    <scroll-view class="address-list" scroll-y>
      <!-- 添加调试信息 -->
      <view v-if="addressList.length === 0" style="padding: 20px;">
        {{ JSON.stringify(addressList) }}
      </view>
      
      <view 
        v-for="address in addressList" 
        :key="address.id" 
        class="address-item"
        :class="{ active: selectedId === address.id }"
        @tap="selectAddress(address)"
      >
        <!-- 左侧图标 -->
        <view class="location-icon">
          <image src="/static/address/location.png" mode="aspectFit" />
        </view>

        <!-- 地址信息 -->
        <view class="address-info">
          <view class="user-info">
            <text class="name">{{ address?.userName || '未知用户' }}</text>
            <text class="phone">{{ formatPhone(address?.phone || '') }}</text>
          </view>
          <view class="address-detail">
            {{ address?.addressName || '地址未填写' }}
          </view>
        </view>

        <!-- 右侧操作按钮 -->
        <view class="address-actions">
          <view 
            class="action-item edit"
            @tap.stop="editAddress(address)"
          >
            <image src="/static/address/edit.png" mode="aspectFit" class="action-icon"/>
          </view>
          <view 
            class="action-item delete"
            @tap.stop="deleteAddress(address)"
          >
            <image src="/static/address/delete.png" mode="aspectFit" class="action-icon"/>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="!addressList.length">
        <image src="/static/logo.png" mode="aspectFit" class="empty-icon"/>
        <text class="empty-text">暂无收货地址</text>
      </view>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="footer">
      <button class="add-btn" @tap="addAddress">
        <image src="/static/address/add.png" mode="aspectFit" class="btn-icon"/>
        <text>新增收货地址</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onShow, onLoad } from '@dcloudio/uni-app';
import {
  deleteAddressUsingPost, listMyAddressVoByPageUsingPost
} from '../../backend/addressController';
import { tokenStore } from '../../store/tokenStore';
import type { API } from '../../backend/typings';

const addressList = ref<API.AddressVO[]>([]);
const store = tokenStore();
const selectedId = ref<number>();
const isSelectMode = ref(false);

// 格式化手机号
const formatPhone = (phone: string = '') => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const res = await listMyAddressVoByPageUsingPost();
    if (res?.code === 0) {
      // 直接使用 data，不需要 records
      if (Array.isArray(res.data)) {
        addressList.value = res.data;
      } else if (res.data?.records) {
        addressList.value = res.data.records;
      } else {
        addressList.value = [];
        console.error('返回的数据格式不正确：', res.data);
      }
    } else {
      console.error('获取地址列表失败：', res?.message);
      uni.showToast({
        title: res?.message || '获取地址列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取地址列表失败：', error);
    uni.showToast({
      title: '获取地址列表失败',
      icon: 'none'
    });
  }
};

// 选择地址
const selectAddress = (address: API.AddressVO) => {
  if (isSelectMode.value) {
    selectedId.value = address.id;
    uni.$emit('addressSelected', address);
    // 延迟返回,确保数据传递完成
    setTimeout(() => {
      uni.navigateBack();
    }, 100);
  }
};

// 新增地址
const addAddress = () => {
  uni.navigateTo({
    url: '/pages/address/edit'
  });
};

// 编辑地址
const editAddress = (address: API.AddressVO) => {
  uni.navigateTo({
    url: `/pages/address/edit?id=${address.id}`
  });
};

// 删除地址
const deleteAddress = async (address: API.AddressVO) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该地址吗？',
    success: async (res) => {
      if (res.confirm && address.id) {
        try {
          const token = store.getToken;
          const result = await deleteAddressUsingPost(
            { id: address.id },
            token ? {
              header: {
                'Authorization': token
              }
            } : undefined
          );
          if (result?.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            fetchAddressList();
          }
        } catch (error) {
          console.error('删除地址失败：', error);
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        }
      }
    }
  });
};

onLoad((options) => {
  // 判断是否是选择模式
  isSelectMode.value = options?.select === 'true';
  fetchAddressList();
});

onShow(() => {
  const token = store.getToken;
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/profile/profile'
      });
    }, 1500);
    return;
  }
  fetchAddressList();
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

.address-list {
  padding: 20rpx;
}

.address-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: flex-start;
  position: relative;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  cursor: pointer;
}

.address-item.active {
  border: 2rpx solid #ff5722;
}

.location-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
}

.location-icon image {
  width: 100%;
  height: 100%;
}

.address-info {
  flex: 1;
  margin-right: 100rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-right: 20rpx;
}

.phone {
  font-size: 28rpx;
  color: #666;
}

.address-detail {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
}

.address-actions {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
  display: flex;
  gap: 24rpx;
}

.action-item {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-icon {
  width: 36rpx;
  height: 36rpx;
}

.empty-state {
  padding: 120rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 40rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.add-btn {
  width: 100%;
  height: 88rpx;
  background: #ff5722;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.btn-icon {
  width: 32rpx;
  height: 32rpx;
}

.address-item:active {
  opacity: 0.8;
}
</style> 